package com.chisheng.student.servlet;

import com.chisheng.common.Page;
import com.chisheng.student.Student;
import com.chisheng.service.impl.StudentServiceImpl;
import com.chisheng.common.StringUtils;
import com.chisheng.student.StudentUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Objects;

/**
 * 分页查询学生请求处理
 *
 * @author chisheng
 * @since 2021-11-05
 */
@WebServlet("/page")
public class QueryPageServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 分页参数封装
        Page<Student> page = Objects.requireNonNull(StudentUtils.populatePage(request));
        // 数据查询
        StudentServiceImpl studentService = new StudentServiceImpl();
        Page<Student> queryPage = studentService.queryPage(page.getCurrent(), page.getSize());
        if (queryPage != null) {
            request.setAttribute("status", true);
            request.setAttribute("page", queryPage);
            // 当没有消息时设定初始化消息
            if (request.getAttribute("message") == null) {
                request.setAttribute("message", String.format("欢迎访问本站，本站共收录学生信息 %d 条，共计 %d 页",
                        queryPage.getTotal(), queryPage.getTotal() / queryPage.getSize()));
            }
        } else {
            request.setAttribute("status", false);
            request.setAttribute("message", "页面数据请求失败");
        }

        // 请求转发
        String path = request.getContextPath();
        RequestDispatcher dispatcher = request.getRequestDispatcher(path + "/list.jsp");
        dispatcher.forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

}
